//
//  SSHomeViewController.swift
//  weibo
//
//  Created by 邵帅 on 16/6/23.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit
import AFNetworking

 let ID = "homeCell"
class SSHomeViewController: SSBaseTableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        
        
        if isLogin {
        
            
            // 登录之后才可以获取数据
            loadData()
            
            
            tableView.registerClass(SSHomeTableViewCell.self, forCellReuseIdentifier: ID)
            
            // 自动计算行高
            tableView.rowHeight = UITableViewAutomaticDimension
            // 第二个设置预估行高
            tableView.estimatedRowHeight = 200
            
            tableView.tableFooterView = activityView
            
            self.tableView.addSubview(refreshView)
            
            // 刷新的数据回调
            refreshView.addTarget(self, action: #selector(SSHomeViewController.loadData), forControlEvents: .ValueChanged)
            
            // 注册通知监听图片点击
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SSHomeViewController.showPicture(_:)), name: kNotificationBigPicture, object: nil)
            
            
        } else {
            
            registerView.setupInfo(true, imageName: "visitordiscover_feed_image_house", lblText: "关注一些人，回这里看看有什么惊喜")
            
        }
        
    }
    
    // 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    // 通知方法
    func showPicture(noti: NSNotification) {
        
        guard let pic_urls = noti.userInfo!["pic_urls"] as? [SSPhotoViewModel],indexPath = noti.userInfo!["indexPath"] as? NSIndexPath else {
            
            return
        }
        
        
        let brower = SSBrowerController(pic_urls: pic_urls, indexPath: indexPath)
        
        presentViewController(brower, animated: true) { 
            
            
        }
    }
    
    
    
    // 懒加载菊花
    private lazy var activityView: UIActivityIndicatorView = {
        
        let actView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
 
        return actView
    }()
    
    private lazy var refreshView: SSRefreshView = SSRefreshView()
  
}

extension SSHomeViewController {
    
    func loadData() {
        
        var since_id = 0
        var max_id = 0
        
            since_id = SSStatusListModel.shareInstance.statusList.first?.model?.id ?? 0
            
            if self.activityView.isAnimating() {
                
                max_id = SSStatusListModel.shareInstance.statusList.last?.model?.id ?? 0
                
                if max_id != 0 {
                    
                    max_id = max_id - 1
                }
                
                since_id = 0
            }
        
            SSStatusListModel.shareInstance.loadData(since_id, max_id: max_id, success:{(coutn) -> () in
                
                self.tableView.reloadData()
                
                if !self.activityView.isAnimating() {
                    // 提示视图
                    self.showMessage(coutn)
                }
                self.activityView.stopAnimating()
                self.refreshView.endRefreshing()
                
                }, falsed: {
                    
                 self.activityView.stopAnimating()
                    
            })
    
    }
  
    // 提示视图
    private func showMessage(count: Int){
        
        let lblH: CGFloat = 44
        
        let label = UILabel(frame: CGRectMake(0,64 - lblH,UIScreen.mainScreen().bounds.size.width,lblH))
        
        label.backgroundColor = UIColor.orangeColor()
        
        if count == 0 {
            
            label.text = "暂时没有微博更新"
        }else {
            
            label.text = "更新了\(count)条微博"
        }
        
        label.textAlignment = .Center
        
        navigationController?.view.insertSubview(label, belowSubview: (navigationController?.navigationBar)!)
        
        UIView.animateWithDuration(1.0, animations: { 
            
            label.transform = CGAffineTransformMakeTranslation(0, lblH)
            }) { (_) in
                
                UIView.animateWithDuration(1.0, animations: { 
                    
                    label.transform = CGAffineTransformIdentity
                    }, completion: { (_) in
                        
                        label.removeFromSuperview()
                })
                
        }
        
        
    }
}



extension SSHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return SSStatusListModel.shareInstance.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath)as! SSHomeTableViewCell
        
        
        let model = SSStatusListModel.shareInstance.statusList[indexPath.row]
        
        cell.model = model
        
        
        if indexPath.row == SSStatusListModel.shareInstance.statusList.count - 1 && !activityView.isAnimating(){
            
            activityView.startAnimating()
            
            loadData()
        }
        
        
        return cell
    }

}


